﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyDMS.DAL;

public partial class TaskPage : PageBaseClass
{
    MyDMSEntity _myDmsEntity = new MyDMSEntity();
    public string TaskName = string.Empty;
    private int _proj_code=0, _task_code=0;
    protected int _dept_code = 0;
    protected int _assgin_code = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 处理参数
        if (Request.QueryString["proj"] != null)
        {
            _proj_code = int.Parse(Request.QueryString["proj"]);
        }
        if (Request.QueryString["task"] != null)
        {
            _task_code = int.Parse(Request.QueryString["task"]);
            var firstOrDefault = _myDmsEntity.Task.FirstOrDefault(t => t.Task_Code == _task_code);
            if (firstOrDefault != null)
            {
                TaskName = firstOrDefault.Task_Title;
                _assgin_code = firstOrDefault.Assigned_To;
            }
            if(_proj_code==0)
            {
                _proj_code = firstOrDefault.Project_Code;
            }
        }
        if (Request.QueryString["dept"] != null)
        {
            _dept_code = int.Parse(Request.QueryString["dept"]);
        }
        
        #endregion

        var orDefault = _myDmsEntity.Project.FirstOrDefault(p => p.Project_Code == _proj_code);
        var _isAnony = orDefault != null && orDefault.Is_Anonymous;
        if (Author.department_Code == _dept_code || _isAnony)
        {
            #region 绑定数据

            var pmDatesource = from dFolder in _myDmsEntity.Folder.Where(df => df.Task_Code == _task_code)
                               join d in _myDmsEntity.Document on dFolder.Folder_Code
                                   equals d.Folder_Code into documents
                               select new
                                          {
                                              dFolder.Folder_Code,
                                              dFolder.Folder_Title,
                                              dFolder.Creation_Date,
                                              dFolder.Folder_Desc,
                                              dFolder.Updation_Date,
                                              Document_Count = documents.Count()
                                          };
            gvProjectsManaged.DataSource = pmDatesource;
            gvProjectsManaged.DataBind();

            var documentDatasource =
                from d in _myDmsEntity.Document.Where(d => d.Task_Code == _task_code)
                select new
                           {
                               d.Document_Code,
                               d.Document_Name,
                               d.Document_Desc,
                               FolderName =
                    _myDmsEntity.Folder.FirstOrDefault(f => f.Folder_Code == d.Folder_Code).Folder_Title,
                               OwnerName =
                    _myDmsEntity.User.FirstOrDefault(uu => uu.User_Code == d.Owner).FirstName +
                    _myDmsEntity.User.FirstOrDefault(uu => uu.User_Code == d.Owner).LastName,
                               DocumentType =
                    _myDmsEntity.DocumentType.FirstOrDefault(dt => dt.DT_Code == d.Document_Type).Type_Name,
                               d.Creation_Date,
                               d.Updation_Date,
                               d.Recieved_Date
                           };
            gvDocuments.DataSource = documentDatasource;
            gvDocuments.DataBind();

            #endregion
        }
    }
    protected void btnShareDocument_Click(object sender, EventArgs e)
    {
        UserDocument uFolder = new UserDocument();
        uFolder.Shared_Date = DateTime.Now;
        uFolder.Shared_By = Author.user_Code;
        uFolder.Share_Comment = txtUserDocumentDesc.Text.Trim();
        uFolder.Is_Active = true;
        uFolder.User_Code = int.Parse(ddlUsers.SelectedItem.Value);


        _myDmsEntity.UserDocument.AddObject(uFolder);
        if (_myDmsEntity.SaveChanges() > 0)
        {
            Response.Redirect("javascript:$('#dialogAddChildren').dialog('close');alert('公开成功');location.reload(true);");
        }
        else
        {
            Response.Redirect("javascript:$('#dialogAddChildren').dialog('close');javascript:alert('公开失败');location.reload(true);");
        }
    }

    protected void btnAddFolder_Click(object sender, EventArgs e)
    {
        Folder uFolder = new Folder();
        uFolder.Creation_Date = DateTime.Now;
        uFolder.Creation_By = Author.user_Code;
        uFolder.Folder_Title = txtFolderTitle.Text.Trim();
        uFolder.Folder_Desc = txtFolderDesc.Text.Trim();
        uFolder.Task_Code = _task_code;


        _myDmsEntity.Folder.AddObject(uFolder);
        if (_myDmsEntity.SaveChanges() > 0)
        {
            Response.Redirect("javascript:$('#dialogAddChildren').dialog('close');alert('添加成功');location.reload(true);");
        }
        else
        {
            Response.Redirect("javascript:$('#dialogAddChildren').dialog('close');javascript:alert('添加失败');location.reload(true);");
        }
    }
    protected void gvProjectsManaged_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName=="OpenChildren")
        {
            int folderCode = Convert.ToInt32(e.CommandArgument);
            Response.Redirect(Request.Url.AbsoluteUri.ToLower().Replace("task.aspx","Folder.aspx") + "&folder=" + folderCode);
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("./UploadDocument.aspx?proj={0}&task={1}",_proj_code,_task_code));
    }
    protected void gvDocuments_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
            Response.Redirect(string.Format("javascript:window.open( 'viewdocument.aspx?doc={0} ', 'newwin ', 'toolbar=no,menubar=no,status=yes,location=no,resizable=no,scrollbars=yes,width=500,height=380,center:   Yes ');", Convert.ToString(e.CommandArgument)));
        }
        if(e.CommandName=="Del")
        {
            int documentCode = Convert.ToInt32(e.CommandArgument);

            Document upDoc = _myDmsEntity.Document.FirstOrDefault(ud => ud.Document_Code == documentCode);
            FileInfo file = new FileInfo(upDoc.File_Path);
            file.Delete();
            _myDmsEntity.Document.DeleteObject(upDoc);
            _myDmsEntity.SaveChanges();

            Task task = _myDmsEntity.Task.FirstOrDefault(t => t.Task_Code == _task_code);
            task.Updation_Date = DateTime.Now;
            _myDmsEntity.SaveChanges();

            Project project = _myDmsEntity.Project.FirstOrDefault(p => p.Project_Code == _proj_code);
            project.Updation_Date = DateTime.Now;
            _myDmsEntity.SaveChanges();

            gvDocuments.DataBind();
            Response.Redirect(Request.Url.AbsoluteUri);
        }
    }


    private void DownloadFile(string filePath)
    {
        //http://dotnetslackers.com/Community/blogs/haissam/archive/2007/04/03/Downloading-Files-C_2300_.aspx

        // Get the physical Path of the file(test.doc)
        //string filepath = );

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filePath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            Response.ContentType = ReturnExtension(file.Extension.ToLower());

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            Response.TransmitFile(file.FullName);

            // End the response
            Response.End();
        }
    }

    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/msword";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
    protected void gvDocuments_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gvDocuments.PageIndex = e.NewPageIndex;
    }
    protected void gvProjectsManaged_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gvProjectsManaged.PageIndex = e.NewPageIndex;

    }
}